<template>
  <div class="main-layout-1">
    <div id="map" ref="map"></div>
  </div>
</template>

<script>
  import 'ol/ol.css'

  import { Map, View, Feature } from 'ol'
  import { Vector as VectorLayer, Tile as TileLayer } from 'ol/layer'
  import { Vector as VectorSource, OSM } from 'ol/source'
  import { fromLonLat } from 'ol/proj'
  import { Point } from 'ol/geom'
  import { Style, Fill, Stroke, Circle } from 'ol/style'
  import { getVectorContext } from 'ol/render'

  const coordinates = [
    ["106.918082", "31.441314"], //重庆
    ["86.36158200334317", "41.42448570787448"], //新疆
    ["89.71757707811526", "31.02619817424643"], //西藏
    ["116.31694544853109", "39.868508850821115"], //北京
    ["103.07940932026341", "30.438580338450862"], //成都
  ]

  export default {
    name: 'blingbling',
    data () {
      return {}
    },
    mounted () {
      this.initMap()
      this.addDynamicPoints(coordinates);
    },
    methods: {
      initMap () {
        this.map = new Map({
          target: 'map',
          view: new View({
            center: fromLonLat([104.912777, 34.730746]), // center 是必备属性，必须显式指定，否则地图不显示
            zoom: 5, // zoom 是必备属性，必须显式指定，否则地图不显示
            constrainResolution: true,
          }),
          layers: [
            new TileLayer({
              source: new OSM(),
            })
          ],
        })
      },
      addDynamicPoints (coordinates) {
        const pointFeatures = []
        let pointLayer = new VectorLayer({
          source: new VectorSource(),
        })
        this.map.addLayer(pointLayer)
        coordinates.forEach(coord => {
          const feature = new Feature({
            geometry: new Point(fromLonLat(coord)),
          })
          pointFeatures.push(feature)
        })
        pointLayer.getSource().addFeatures(pointFeatures)

        let radius = 0
        pointLayer.on('postrender', e => {
          if (radius >= 20) radius = 0
          const opacity = (20 - radius) * (1 / 20) // radius 为0时可见度为1，为20时可见度为0
          const pointStyle = new Style({
            image: new Circle({
              radius,
              stroke: new Stroke({
                color: `rgba(255, 0, 0, ${opacity})`,
                width: 3 - radius/10 // radius 为0时线宽为3，radius为20时线宽为1
              })
            })
          })

          let vectorContext = getVectorContext(e)
          vectorContext.setStyle(pointStyle) // 对vectorContext上下文指定统一样式
          pointFeatures.forEach(feature => {
            vectorContext.drawGeometry(feature.getGeometry())
          })
          radius += 0.2
          this.map.render()
        })
      },
    },
  }
</script>

<style scoped>
#map {
  height: 100%;
}
</style>
